package com.diy.sigmund.diyuser.my.game.typing;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.swing.JPanel;

/**
 * @author ylm-sigmund
 * @since 2021/8/10 9:26
 */
public class MyPanel extends JPanel implements Runnable, KeyListener {

    char[] c = new char[10];
    int[] x = new int[10];
    int[] y = new int[10];
    /** 初始积分1000分 */
    int integral = 1000;

    public MyPanel() {
        for (int i = 0; i < 10; i++) {
            c[i] = (char) (Math.random() * 26 + 97);
            x[i] = (int) (Math.random() * 300);
            y[i] = (int) (Math.random() * 50);
        }
    }

    @Override
    public void paint(Graphics g) {
        // 继承JPanel并初始化父类可大幅度解决画面刷新、视觉疲劳
        super.paint(g);
        if (integral > 0) {
            // 设置元素颜色
            g.setColor(Color.BLACK);
            for (int i = 0; i < 10; i++) {
                final String str = Character.toString(c[i]).toUpperCase(Locale.ROOT);
                // 1.出现的元素，2.元素的x轴，3.元素的y轴
                g.drawString(str, x[i], y[i]);
            }
            // 显示积分在屏幕上
            g.setColor(Color.RED);
            g.drawString("你的成u绩是：" + integral, 10, 15);
            return;
        }
        g.setColor(Color.RED);
        g.drawString("GAME OVER", 100, 170);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        final char keyChar = e.getKeyChar();
        System.out.println(keyChar);
        boolean equal = false;
        for (int i = 0; i < 10; i++) {
            if (Objects.equals(keyChar, c[i])) {
                equal = true;
                c[i] = (char) (Math.random() * 26 + 97);
                x[i] = (int) (Math.random() * 300);
                y[i] = 0;
                integral += 100;
                System.out.println("想等");
                break;
            }
        }
        if (!equal) {
            integral -= 100;
            System.out.println("不相等");
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void run() {
        while (integral > 0) {
            for (int i = 0; i < 10; i++) {
                y[i]++;
                // 窗体边框战友一部分像素，所以设置该值即可
                if (y[i] > 370) {
                    y[i] = 0;
                    c[i] = (char) (Math.random() * 26 + 97);
                    x[i] = (int) (Math.random() * 300);
                    integral -= 100;
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 重新绘制
                repaint();
            }
        }
    }
}
